<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>检查运输计划数据</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
      max-width: 800px;
      margin: 0 auto;
      background-color: #f5f5f5;
    }

    .container {
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
    }

    h1,
    h2 {
      color: #333;
      border-bottom: 2px solid #409EFF;
      padding-bottom: 10px;
    }

    .form-group {
      margin-bottom: 15px;
    }

    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
      color: #555;
    }

    input {
      width: 100%;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
    }

    button {
      background: #409EFF;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-right: 10px;
    }

    button:hover {
      background: #337ecc;
    }

    .result {
      margin-top: 20px;
      padding: 15px;
      border: 1px solid #e6e6e6;
      border-radius: 4px;
      background: #fafafa;
      white-space: pre-wrap;
      font-family: monospace;
      max-height: 400px;
      overflow-y: auto;
    }

    .error {
      color: #F56C6C;
      background: #FEF0F0;
      padding: 10px;
      border-radius: 4px;
      margin: 10px 0;
    }

    .success {
      color: #67C23A;
      background: #F0F9FF;
      padding: 10px;
      border-radius: 4px;
      margin: 10px 0;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 15px;
    }

    th,
    td {
      padding: 8px 12px;
      text-align: left;
      border-bottom: 1px solid #eee;
    }

    th {
      background: #f8f9fa;
      font-weight: bold;
    }
  </style>
</head>

<body>
  <div class="container">
    <h1>🔍 检查运输计划数据</h1>

    <div class="form-group">
      <label for="billNo">运单编号:</label>
      <input type="text" id="billNo" placeholder="例如: YD202412250001" value="YD202412250001">
    </div>

    <button onclick="checkData()">检查数据</button>
    <button onclick="generateData()">生成测试数据</button>
    <button onclick="clearResult()">清空结果</button>
  </div>

  <div class="container">
    <h2>📋 检查结果</h2>
    <div id="result"></div>
  </div>

  <script>
    const baseURL = 'http://localhost:8080';

    function showResult (title, data) {
      const resultDiv = document.getElementById('result');
      resultDiv.innerHTML = `
                <h3>${title}</h3>
                <div class="result">${JSON.stringify(data, null, 2)}</div>
            `;
    }

    function showError (message) {
      document.getElementById('result').innerHTML = `<div class="error">❌ 错误: ${message}</div>`;
    }

    function showSuccess (message) {
      document.getElementById('result').innerHTML = `<div class="success">✅ ${message}</div>`;
    }

    function clearResult () {
      document.getElementById('result').innerHTML = '';
    }

    // 检查运输计划数据
    async function checkData () {
      const billNo = document.getElementById('billNo').value;
      if (!billNo) {
        showError('请输入运单编号');
        return;
      }

      try {
        console.log('检查运输计划数据，运单编号:', billNo);

        // 1. 查询运输计划
        const response = await fetch(`${baseURL}/system/plan/list?billNo=${encodeURIComponent(billNo)}`);
        const data = await response.json();

        console.log('查询结果:', data);

        let resultHtml = `
                    <h3>🔍 运输计划数据检查结果</h3>
                    <div class="result">API响应: ${JSON.stringify(data, null, 2)}</div>
                `;

        if (data.code === 200) {
          if (data.rows && data.rows.length > 0) {
            resultHtml += `
                            <div class="success">✅ 找到 ${data.rows.length} 条运输计划记录</div>
                        `;

            // 显示数据表格
            resultHtml += `
                            <h4>运输计划数据:</h4>
                            <table>
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>运单编号</th>
                                        <th>城市</th>
                                        <th>省份</th>
                                        <th>节点类型</th>
                                        <th>经过顺序</th>
                                        <th>预计耗时</th>
                                        <th>创建时间</th>
                                    </tr>
                                </thead>
                                <tbody>
                        `;

            data.rows.forEach((plan, index) => {
              resultHtml += `
                                <tr>
                                    <td>${plan.id || '-'}</td>
                                    <td>${plan.billNo || '-'}</td>
                                    <td>${plan.city || '-'}</td>
                                    <td>${plan.province || '-'}</td>
                                    <td>${plan.nodeType || '-'}</td>
                                    <td>${plan.passOrder || '-'}</td>
                                    <td>${plan.estimatedDuration || '-'}</td>
                                    <td>${plan.createTime || '-'}</td>
                                </tr>
                            `;
            });

            resultHtml += `
                                </tbody>
                            </table>
                        `;
          } else {
            resultHtml += `
                            <div class="error">❌ 未找到运输计划记录</div>
                            <p>可能的原因：</p>
                            <ul>
                                <li>数据库中还没有该运单的运输计划数据</li>
                                <li>运单编号不匹配</li>
                                <li>需要先生成运输计划</li>
                            </ul>
                        `;
          }
        } else {
          resultHtml += `
                        <div class="error">❌ 查询失败: ${data.msg || '未知错误'}</div>
                    `;
        }

        document.getElementById('result').innerHTML = resultHtml;

      } catch (error) {
        console.error('检查数据异常:', error);
        showError('检查数据异常: ' + error.message);
      }
    }

    // 生成测试数据
    async function generateData () {
      const billNo = document.getElementById('billNo').value;
      if (!billNo) {
        showError('请输入运单编号');
        return;
      }

      try {
        showResult('生成测试数据', '开始生成...');

        // 1. 调用城市运输分析接口
        console.log('调用城市运输分析接口...');
        const analysisResponse = await fetch(`${baseURL}/pack/locationLog/analysis/cityTransit?departureCity=长春&destinationCity=天津`);
        const analysisData = await analysisResponse.json();

        console.log('城市运输分析结果:', analysisData);

        if (analysisData.code !== 200) {
          showError('获取城市运输分析数据失败: ' + (analysisData.msg || '未知错误'));
          return;
        }

        if (!analysisData.data || !analysisData.data.passedCities || analysisData.data.passedCities.length === 0) {
          showError('未获取到有效的运输路径数据');
          return;
        }

        // 2. 保存运输计划
        console.log('开始保存运输计划...');
        const passedCities = analysisData.data.passedCities;
        const saveResults = [];

        for (let i = 0; i < passedCities.length; i++) {
          const cityInfo = passedCities[i];

          let nodeType = '途经点';
          if (i === 0) {
            nodeType = '起点';
          } else if (i === passedCities.length - 1) {
            nodeType = '终点';
          }

          const planData = {
            waybillId: 1,
            billNo: billNo,
            locatorId: 1,
            locatorCode: 'LOC001',
            province: cityInfo.provinceName || '',
            city: cityInfo.cityName || '',
            district: '',
            estimatedDuration: cityInfo.averageStayTime || 0,
            nodeType: nodeType,
            passOrder: cityInfo.passOrder || (i + 1)
          };

          console.log(`保存第${i + 1}条运输计划:`, planData);

          const saveResponse = await fetch(`${baseURL}/system/plan`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(planData)
          });
          const saveResult = await saveResponse.json();

          saveResults.push({
            index: i,
            planData: planData,
            result: saveResult
          });

          console.log(`第${i + 1}条保存结果:`, saveResult);
        }

        showResult('运输计划生成结果', saveResults);

        // 3. 重新检查数据
        setTimeout(() => {
          checkData();
        }, 1000);

      } catch (error) {
        console.error('生成数据异常:', error);
        showError('生成数据异常: ' + error.message);
      }
    }

    // 页面加载完成后的初始化
    document.addEventListener('DOMContentLoaded', function () {
      console.log('检查运输计划数据页面已加载');
    });
  </script>
</body>

</html>